<template>
  <div>
    <el-dialog
      :title="config.title"
      v-el-drag-dialog
      :visible="config.show===true"
      :close-on-click-modal="false"
      width="40%"
      :before-close="handleClose"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="上级菜单：" prop="parentCatalog" v-show="config.itemShow.parentCatalog">
          <el-select
            v-model="form.parentCatalog"
            placeholder="请选择"
            ref="parentCatalogSelect"
            style="width: 100%"
          >
            <el-input
              class="input"
              placeholder="输入关键字进行过滤"
              prefix-icon="el-icon-search"
              v-model="parentCatalogFilter"
              size="mini"
              clearable
            ></el-input>
            <el-option hidden key="id" :value="form.parentCatalog" :label="form.parentCatalogName">
            </el-option>
            <el-tree
              :data="param.parentCatalogTreeData"
              :props="defaultProps"
              @node-click="handleNodeClick"
              :expand-on-click-node="false"
              :check-on-click-node="true"
              accordion
              ref="tree"
              node-key="id"
              :default-expand-all="false"
              :filter-node-method="filterNode"
            >

              <span slot-scope="{ data }">
                <span>{{ data.label }}</span>
                <!-- 2022年3月31日 LQ 这个没什么用啊，先去掉
                 <el-tag
                      size="mini"
                      style="margin: 0 10px"
                      v-show="filterorgType(data.tag)"
                  >{{ filterorgType(data.tag) }}</el-tag
                  >-->
              </span>
            </el-tree>
          </el-select>
        </el-form-item>
        <el-form-item label="目录名称：" prop="name" v-show="config.itemShow.name">
          <el-input v-model="form.name" type="text"></el-input>
        </el-form-item>
        <el-form-item label="是否可用：" v-show="config.itemShow.isValid">
          <el-switch v-model="form.isValid"></el-switch>
        </el-form-item>
        <el-form-item label="角色权限：" v-show="config.itemShow.roles">
          <el-select v-model="form.roles" value-key="value" ref="rolesSelect" multiple clearable filterable
                     placeholder="请选择允许访问的角色"
          >
            <el-option v-for="role in param.portalRoles" :key="role.value" :label="role.name"
                       :value="role.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-row>
          <el-form-item label="图标名称：">
            <el-col :span="8">
              <el-upload
                ref="catalogIconUpload"
                class="upload-demo"
                :action="' '"
                accept=".png,.jpg,.jpeg,.gif"
                :auto-upload="false"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :on-change="catalogIconHandleChangeImg"
                :file-list="catalogIconFileList"
                :show-file-list="false"
              >
                <el-button slot="trigger" size="small" type="primary">上传图片</el-button>
                <!--                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>-->
              </el-upload>
            </el-col>
            <el-col :span="16">
              <template v-if="hasCatalogIcon">
                <el-image :src="catalogIconUrl" :preview-src-list="[catalogIconUrl]"
                          style="height: 30px;"
                ></el-image>
                <el-link class="upload-img-linkText" type="success" :href="catalogIconUrl" target="_blank">{{form.enflag}}</el-link>
              </template>
            </el-col>
          </el-form-item>
          <el-col :span="24">
            <el-form-item label="说明：">
              <el-input type="textarea" :rows="2" v-model="form.explain" placeholder="服务的扩展说明"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
				<el-button type="primary" @click="handleOk">{{ config.okBtnText }}</el-button>
				<el-button @click="handleClose">取消</el-button>
			</span>
    </el-dialog>
  </div>
</template>

<script>
import elDragDialog from '@/directive/el-dragDialog/'
import bus from '@/utils/bus'
import { insertDir, updateDir, uploadCatalogIconFile } from '@/api/resource/resourceCatalog'
import { requestBaseUrl } from '@/utils/request'
import * as gcf from '@/utils/Global/GlobalCommonFunction'

export default {
  name: 'editCatalogDir',
  data() {
    return {
      parentCatalogFilter: '',
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      catalogIconFileList:[],
      rules: {
        parentCatalog: [{ required: true, message: '请选择上级菜单', trigger: 'blur' }],
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
      }
    }
  },
  directives: {//到这里了，看看自定义组件怎么个用法
    elDragDialog
  },
  props: {
    config: {
      type: Object,
      default() {
        return {
          title: '',
          show: false,
          itemShow: {
            parentCatalog: false,
            name: true,
            isValid: true,
            roles: true
          },
          okBtnText: '确定'
        }
      }
    },
    param: {
      type: Object,
      default() {
        return {
          parentCatalogTreeData: [],
          portalRoles: []
        }
      }
    },
    form: {
      type: Object,
      default() {
        return {
          operatetype: '',
          parentCatalog: '',
          parentCatalogName: '', // select框显示的name
          isValid: true,
          name: '',
          roles: [],
          id: '',
          sortid: 1,
          enflag: '',
          explain: ''
        }
      }
    }
  },
  computed:{
    hasCatalogIcon(){
      return gcf.IsNotNullStr(this.form.enflag);
    },
    catalogIconUrl(){
      return requestBaseUrl+this.form.enflag
    }
  },
  methods: {
    handlePreview(file) {
      console.log(file);
    },
    handleRemove(file,legendFileList) {
      console.log(file);
    },
    catalogIconHandleChangeImg(file,iconFileList){
      let that = this;
      that.catalogIconFileList = iconFileList;
      const typeArr = ['image/png','image/gif','image/jpeg','image/jpg'];
      const isJPG = typeArr.indexOf(file.raw.type)!==-1;
      const isLt5M = file.size/1024/1024<5;
      if(!isJPG){
        that.$message.error("只能上传图片！");
        that.$refs.catalogIconUpload.clearFiles();
        that.catalogIconFileList = [];
        return;
      }
      if(!isLt5M){
        that.$message.error("上传图片大小不能超过 5MB！");
        that.$refs.catalogIconUpload.clearFiles();
        that.catalogIconFileList = [];
        return;
      }
      const iconFile = file.raw;
      const formData = new FormData();
      formData.append('file', iconFile);
      uploadCatalogIconFile(formData).then(res=>{
        that.form.enflag = res.catalogIconPath;
        that.$forceUpdate();
      }).catch(resp => {
        console.log('uploadCatalogIconFile', resp.status + "," + resp.statusText);
      });
    },
    handleClose() {
      let that = this
      that.config.show = false
    },
    handleOk() {
      let that = this
      let param = {
        'pid': that.form.parentCatalog,
        'name': that.form.name,
        'sortid': that.form.sortid,
        'roleid': that.form.roles.join(','),
        'isvalid': that.form.isvalid ? 1 : 0,
        'enflag': that.form.enflag,
        'explain': that.form.explain
      }
      if (that.form.operatetype == 'updateDir') {
        param.id = that.form.id
        updateDir(param).then((res) => {
          bus.$emit('refreshResourceCatalog')
          that.config.show = false
        }).catch(resp => {
          console.log('resourceCatalogInsertDir', resp.status + ',' + resp.statusText)
        })
      }
      if (that.form.operatetype == 'insertDir') {
        insertDir(param).then((res) => {
          bus.$emit('refreshResourceCatalog')
          that.config.show = false
        }).catch(resp => {
          console.log('resourceCatalogInsertDir', resp.status + ',' + resp.statusText)
        })
      }
    },

    // 结构树点击事件
    handleNodeClick(currentData) {
      let that = this
      that.form.parentCatalog = currentData.id // select绑定值为点击的选项的value
      that.form.parentCatalogName = currentData.label // input中显示值为label
      that.parentCatalogFilter = '' // 点击后搜索框清空
      that.form.sortid = 1
      for (let i in currentData.children) {
        let sortIndex = currentData.children[i]['sortid']
        if (that.form.sortid <= sortIndex) {
          that.form.sortid = sortIndex
        }
      }
      that.$refs.parentCatalogSelect.blur() // 点击后关闭下拉框，因为点击树形控件后select不会自动折叠

    },
    // 模糊查询（搜索过滤），实质为筛选出树形控件中符合输入条件的选项，过滤掉其他选项
    filterNode(value, data) {
      if (!value) return true
      let filterRes = data.label.indexOf(value) !== -1
      return filterRes
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-select {
  width: 100%;
}

::v-deep .el-form-item__label {
  padding: 0px;
}
</style>
